package com.javaee.ejb.session;

import java.util.List;

import com.javaee.ejb.entity.Activity;
import com.javaee.ejb.session.remote.ActivityManagerRemote;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 * Session Bean implementation class ActivityManager
 */
@Stateless
public class ActivityManager implements ActivityManagerRemote {

	@PersistenceContext
	private EntityManager entityManager;

	public ActivityManager() {
	}

	public int saveActivity(Activity activity) {
		activity = entityManager.merge(activity);
		entityManager.persist(activity);
		return activity.getId();
	}

	@SuppressWarnings("unchecked")
	public List<Activity> getListByEmployeeId(int employeeId, Boolean isValid) {
		StringBuilder req = new StringBuilder(
				"SELECT DISTINCT activity FROM Activity activity INNER JOIN activity.collaborator collaborator");
		req.append(" WHERE collaborator.id = :employeeId");
		if (isValid != null)
			req.append(" AND activity.isValid = :isValid");
		req.append(" ORDER BY activity.day DESC, activity.id DESC");

		Query query = entityManager.createQuery(req.toString());
		query.setParameter("employeeId", employeeId);
		if (isValid != null)
			query.setParameter("isValid", isValid);

		return (List<Activity>) query.getResultList();
	}

	@SuppressWarnings("unchecked")
	public List<Activity> getLastActivitiesListByEmployeeIdWithProject(
			int employeeId, int nbActivies) {
		Query query = entityManager
				.createQuery("SELECT DISTINCT activity FROM Activity activity INNER JOIN activity.collaborator collaborator INNER JOIN FETCH activity.project WHERE collaborator.id = :employeeId ORDER BY activity.day DESC, activity.id DESC");
		query.setParameter("employeeId", employeeId);
		query.setMaxResults(nbActivies);

		return (List<Activity>) query.getResultList();
	}

	@SuppressWarnings("unchecked")
	public List<Activity> getListByProjectId(int projectId) {
		Query query = entityManager
				.createQuery("SELECT DISTINCT activity FROM Activity activity INNER JOIN activity.project project WHERE project.id = :projectId ORDER BY activity.day DESC, activity.id DESC");
		query.setParameter("projectId", projectId);
		return (List<Activity>) query.getResultList();
	}

	@Override
	public Activity getById(int activityId) {
		return entityManager.find(Activity.class, activityId);
	}
}
